package com.example.riseofthedefender;

import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.PointF;
import android.util.FloatMath;


public class Bullet extends Square{

	public static int current = 0;
	public static ArrayList<Bullet> arrayList;
	public static void initArrayList(int size)
	{
		arrayList = new ArrayList<Bullet>(size);
		for(int i = 0; i < size; ++i)
			arrayList.add(new Bullet());
	}
	public static int getNext()
	{
		++current;
		if(current >= arrayList.size())
			current = 0;
		return current;
	}
	private short duration = 0;
	private final short durationMax = 30;
	
	public Bullet()
	{
		wHlv = 40.0f;
		hHlv = 10.0f;
	}
	
	public void shoot(float x, float y, float rotationR)
	{
		this.duration = durationMax;
		this.rotateD = rotationR * MyMath.R2D;
		this.xV = FloatMath.cos(rotationR);
		this.yV = FloatMath.sin(rotationR);
		this.pos.x = x;
		this.pos.y = y;
	}
	
	public void update()
	{
		if(duration<=0)
			return;
		--duration;
		pos.x += xV * 14;
		pos.y += yV * 14;
		checkCollision();
	}

	private PointF newPos = new PointF();
	private Ball b;
	private void checkCollision() {
		for(int i = 0; i < Ball.arrayList.size(); ++i)
		{
			b = Ball.arrayList.get(i);
			
			if(b.pos.x + b.wHlv < pos.x - wHlv)
				continue;
			if(b.pos.x - b.wHlv > pos.x + wHlv)
				continue;
			if(b.pos.y - b.hHlv > pos.y + hHlv)
				continue;
			if(b.pos.y + b.hHlv < pos.y - hHlv)
				continue;
			
			newPos.set(pos.x+xV*(Math.abs(wHlv-hHlv)), pos.y+yV*(Math.abs(wHlv-hHlv)));

			if(MyMath.distance(newPos, b.pos) < hHlv + b.hHlv)
				b.pos.y += GameVar.cHeight;
		}
	}
	
	public void draw(GL10 gl) {
		if(duration<=0)
			return;
		
		gl.glLoadIdentity();

		gl.glTranslatef(-Camera.pos.x,-Camera.pos.y,0.0f);
		gl.glTranslatef(pos.x, pos.y, 0.0f);
		gl.glRotatef(rotateD, 0, 0, 1);
		gl.glScalef(wHlv, hHlv, 1.0f);
		
		gl.glBindTexture(GL10.GL_TEXTURE_2D, TextureManager.LAZER.textures[0]);
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
	}
}
